import React, { ChangeEventHandler, useState, ChangeEvent, useRef, useEffect } from 'react';
import './LoginYunNan.scss';
import { BrowserRouter, Routes, Route, Link, Navigate, useNavigate } from 'react-router-dom'
import { Button, Space, Segmented, Input, Checkbox } from 'antd';
import {
    UserOutlined,
    RightOutlined,
    SafetyCertificateOutlined,
    MobileOutlined,
    LockOutlined,
    LoadingOutlined
} from '@ant-design/icons';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { SegmentedValue } from 'antd/es/segmented';
import { deepClone, getChangeEventValue, isEmpty, toastShort } from '../../utils';
import systemApi from '../../api/system';
import redux from './../../redux/store';
import { setSystemConfig } from '../../redux/system.slice';
import { saasConfig } from '../../config/theme-config';

const Login = () => {

    const navigate = useNavigate();
    const [account, setAccount] = useState('');
    const [password, setPassword] = useState('');
    const [phone, setPhone] = useState('');
    const [code, setCode] = useState('');
    const [codeLoading, setCodeLoading] = useState(false);
    const [codeSending, setCodeSending] = useState(true);
    const [loginLoading, setLoginLoading] = useState(false);
    const [countTime, setCountTime] = useState<number>(59);
    const [remenberMe, setRemenberMe] = useState(true);
    // const [loginMethod, setLoginMethod] = useState<SegmentedValue>('手机验证码登录');
    const [loginMethod, setLoginMethod] = useState<SegmentedValue>('账号密码登录');
    const countTimeRef = useRef<number>(59);
    const delayTimer = useRef<any>(null);

    useEffect(() => {
        const init_phone = localStorage.getItem('phone');
        const init_account = localStorage.getItem('account');
        setPhone(init_phone ? init_phone : "");
        setAccount(init_account ? init_account : "");
        return () => {
            // console.log("销毁1")
            delayTimer.current && clearTimeout(delayTimer.current);
        }
    }, []);

    useEffect(() => {
        //页面初始化时，挂载监听事件
        document.addEventListener('keydown', onkeydown);
        return () => {
            // console.log("销毁2")
            document.removeEventListener('keydown', onkeydown)
        }
    }, [phone, code, account, password]);

    const onkeydown = (e: any) => {
        if (e.code == 'Enter' && checkLoginBtnEnable()) {
            handleLogin();
        }
    };

    const jumpToRegister = () => {
        navigate('/register')
    }

    const onLoginMethodChange = (e: SegmentedValue) => {
        console.log("onLoginMethodChange---->", e);
        setLoginMethod(e)
    };

    const onPhoneTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        if (getChangeEventValue(e).length > 11) {
            return toastShort('warning', '手机号最长不超过11位')
        }
        setPhone(getChangeEventValue(e))
    }

    const onCodeTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setCode(getChangeEventValue(e))
    }

    const onAccountTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setAccount(getChangeEventValue(e))
    }

    const onPasswordTextChange = (e: ChangeEvent<HTMLInputElement>) => {
        setPassword(getChangeEventValue(e))
    }

    const onCheckBoxChange = (e: any) => {
        console.log("onCheckBoxChange", e)
        setRemenberMe(e.target.checked)
    };

    const checkLoginBtnEnable = (): boolean => {
        let loginBtnEnable = false;
        if (loginMethod == '手机验证码登录') {
            console.log("phone", phone, code)
            if (phone.length == 11 && code.length == 4) {
                loginBtnEnable = true;
            }
        } else {
            if (!isEmpty(account) && !isEmpty(password)) {
                loginBtnEnable = true;
            }
        }
        return loginBtnEnable;
    };

    const handleSendCode = () => {
        if (phone.length == 0) {
            return toastShort('error', '请输入手机号')
        }
        if (phone.length !== 11) {
            return toastShort('error', '请输入合法的手机号')
        }
        if (codeLoading) {
            return false;
        }
        setCodeLoading(true);
        setCodeSending(true)
        delayTimer.current = setTimeout(() => {
            setCodeSending(false);
            startCountDown();
            toastShort('success', '验证码已发送，请查收')
        }, 2000);
    }

    const startCountDown = () => {
        if (countTimeRef.current == 0) {
            console.log("倒计时结束------->");
            setCodeLoading(false);
            setCodeSending(true);
            countTimeRef.current = 59;
            setCountTime(59);
            return false;
        }
        delayTimer.current = setTimeout(() => {
            const newCountTime = countTimeRef.current - 1;
            setCountTime(newCountTime);
            countTimeRef.current = newCountTime;
            startCountDown();
        }, 1000)
    }

    const handleLogin = () => {
        if (!checkLoginBtnEnable()) {
            return false;
        }
        let params = {};
        if (loginMethod === '手机验证码登录') {
            params = {
                type: '2',
                phone: phone,
                data: code
            }
            if (remenberMe) {
                localStorage.setItem('phone', phone);

            } else {
                localStorage.removeItem('phone');
            }
            localStorage.removeItem('account')
        } else {
            params = {
                type: '1',
                phone: account,
                data: password
            }
            if (remenberMe) {
                localStorage.setItem('account', account)
            } else {
                localStorage.removeItem('account')
            }
            localStorage.removeItem('phone')
        }
        setLoginLoading(true)
        systemApi.login(params)
            .then(res => {
                //@ts-ignore
                const token: string = res.data.token;
                localStorage.setItem('token', token);
                systemApi.getUserInfo({})
                    .then(res => {
                        //@ts-ignore
                        let userInfo = res.data;
                        let systemConfig = deepClone(redux.getState().systemConfig);
                        systemConfig.userInfo = userInfo;
                        systemConfig.token = token;
                        redux.dispatch(setSystemConfig(systemConfig))
                        localStorage.setItem('systemConfig', JSON.stringify(systemConfig));
                        setLoginLoading(false);
                        navigate('/')
                        window.location.reload();
                    })
                    .catch(err => {
                        toastShort("error", "登陆失败，请您稍后重试")
                        setLoginLoading(false);
                    })

            })
            .catch(err => {
                toastShort("error", "登陆失败，请您稍后重试")
                setLoginLoading(false)
            })
    }

    return (
        <div className='login-page'>
            <div className='login-left'>
                <div className='login-left-info'>
                    <div className='login-system-header-box'>
                        <div className='login-system-header-img'>
                            <img
                                style={{ width: '100%', height: '100%' }}
                                src={saasConfig.themeLogoPath}
                                alt=""
                            />
                        </div>
                        <div className='login-system-header-content'>
                            <div className='login-system-header-assistant'>云南省林业调查规划院</div>
                            {/* <div className='login-system-header-text'>自然保护地总规快速编制利器</div> */}
                        </div>
                    </div>
                    <div className='login-system-slogan-box'>
                        <div className='login-system-slogan-text'>
                            规划科学是最大的效益
                        </div>
                        <div className='login-system-slogan-text'>
                            规划失误是最大的浪费
                        </div>
                        <div className='login-system-slogan-text'>
                            规划折腾是最大的忌讳
                        </div>
                        <div className='flex-row slogan-sign'>
                            <div className='slogan-sign-line'></div>
                            习近平
                        </div>
                    </div>
                    <div className='login-system-bottom-box'>

                    </div>
                </div>
            </div>
            <div className='login-right'>
                <div className='login-box'>
                    {/* <div className='login-right-title' style={{ marginBottom: 14 }}>自然保护地规划编制</div>
                    <div className='login-right-title-system'>智能辅助系统</div> */}
                    <div className='login-right-title' style={{ marginBottom: 14 }}>自然保护地规划</div>
                    <div className='login-right-title-system'>智慧辅助系统</div>
                    {/* <div className='flex-row login-right-now'>没有账户，
                        <div
                            onClick={jumpToRegister}
                            className='flex-row switch-btn'
                        >
                            前往注册
                            <div className='switch-btn-icon-container'>
                                <RightOutlined className='switch-btn-icon' color='#fff' />
                            </div>
                        </div>
                    </div> */}
                    {/* <Segmented
                        className='login-right-block'
                        options={['手机验证码登录', '账号密码登录']}
                        size="large"
                        onChange={onLoginMethodChange}
                        value={loginMethod}
                        block
                    /> */}
                    {
                        loginMethod === '手机验证码登录' ?
                            <React.Fragment>
                                <Input
                                    className='login-right-input'
                                    maxLength={11}
                                    placeholder="请输入手机号"
                                    prefix={<MobileOutlined />}
                                    size={'large'}
                                    onChange={onPhoneTextChange}
                                    value={phone}
                                    type={'number'}
                                />
                                <Input
                                    className='login-right-input'
                                    suffix={
                                        <div onClick={handleSendCode} className='send-code-btn'>
                                            {
                                                //是否可以继续发送验证码
                                                codeLoading ?
                                                    <React.Fragment>
                                                        {
                                                            //是否在发送中
                                                            codeSending ?
                                                                <LoadingOutlined />
                                                                :
                                                                <span>{countTime}秒后获取</span>
                                                        }
                                                    </React.Fragment>
                                                    :
                                                    '获取验证码'
                                            }
                                        </div>
                                    }
                                    placeholder="请输入验证码"
                                    prefix={<SafetyCertificateOutlined color={'#0f6432'} />}
                                    size={'large'}
                                    maxLength={4}
                                    onChange={onCodeTextChange}
                                    value={code}
                                />
                            </React.Fragment>
                            :
                            <React.Fragment>
                                <Input
                                    className='login-right-input'
                                    maxLength={20}
                                    placeholder="请输入账号"
                                    prefix={<UserOutlined style={{ color: '#0f6432' }} />}
                                    size={'large'}
                                    onChange={onAccountTextChange}
                                    value={account}
                                />
                                <Input
                                    className='login-right-input'
                                    placeholder="请输入密码"
                                    prefix={<LockOutlined style={{ color: '#0f6432' }} />}
                                    size={'large'}
                                    maxLength={20}
                                    onChange={onPasswordTextChange}
                                    value={password}
                                    type={'password'}
                                />
                            </React.Fragment>
                    }
                    <Checkbox
                        className='login-right-checkbox'
                        checked={remenberMe}
                        onChange={onCheckBoxChange}
                    >记住账号</Checkbox>
                    <Button
                        className='login-right-botton'
                        onClick={handleLogin}
                        type="primary"
                        disabled={!checkLoginBtnEnable()}
                        loading={loginLoading}
                    >
                        登录
                    </Button>
                    <div
                        className='login-right-text'>
                        点击
                        <span className='login-right-color'>登录</span>
                        表示已阅读并同意
                        <span className='login-right-color'>服务条款</span>
                    </div>
                </div>
            </div>
            <div className='super-company link-text' title='青远生态规划助手官方网址' onClick={() => window.open('https://www.zhbhd.cn/addons/256.html')}>
                北京青远生态技术支持
            </div>
        </div>
    )
}

export default Login;